package com.fubowen.lepton.ui.container

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import com.fubowen.lepton.R
import com.fubowen.lepton.conf.SiteConfigViewModel
import com.fubowen.lepton.databinding.FragmentManagerBinding
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator


class ManagerFragment : Fragment() {

    private lateinit var controller: NavController
    private lateinit var binding: FragmentManagerBinding
    private val viewModel: SiteConfigViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentManagerBinding.inflate(inflater, container, false)
        controller = findNavController()
        val viewPager = binding.managerViewPager
        val tabLayout = binding.managerTabLayout
        val adapter = TabAdapter(requireActivity())
        viewPager.adapter = adapter
        val view = viewPager.getChildAt(0)
        view.overScrollMode = View.OVER_SCROLL_NEVER
        TabLayoutMediator(tabLayout, viewPager, true) { tab: TabLayout.Tab, position: Int ->
            when (position) {
                0 -> {
                    tab.text = "书签"
                }

                1 -> {
                    tab.text = "历史"
                }

                2 -> {
                    tab.text = "下载"
                }
            }
        }.attach()
        binding.managerBack.setOnClickListener {
            goBackImpl()
        }
        goBack()
        return binding.root
    }

    private fun goBack() {
        val onBackCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                goBackImpl()
                isEnabled = false
            }
        }
        requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, onBackCallback)
    }

    private fun goBackImpl() {
        controller.popBackStack(R.id.homeFragment, inclusive = false, saveState = true)
    }
}

